package org.androidpush.client;

import java.io.Serializable;
import java.util.List;
import java.util.Properties;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Log;

import org.androidpush.activity.ChatActivity;
import org.androidpush.activity.NotificationSettingsActivity;
import org.androidpush.greendao.ChatMsg;
import org.androidpush.utils.ConstantUtils;
import org.jivesoftware.smack.packet.IQ;

/**
 * Created by 2017/4/13
 * @author huang
 */
public final class ServiceManager implements Serializable{

    private static final String LOGTAG = LogUtil
            .makeLogTag(ServiceManager.class);

    private Context context;

    private SharedPreferences sharedPrefs;

    private Properties props;

    private String version = "0.5.0";

    private String apiKey;

    private String xmppHost;

    private String xmppPort;

    private String callbackActivityPackageName;

    private String callbackActivityClassName;

//    private BroadcastReceiver chatMsgReceiver;

    public ServiceManager(Context context) {
        this.context = context;

        if (context instanceof Activity) {
            Log.i(LOGTAG, "Callback Activity...");
            Activity callbackActivity = (Activity) context;
            callbackActivityPackageName = callbackActivity.getPackageName();
            callbackActivityClassName = callbackActivity.getClass().getName();
        }

        props = loadProperties();
        apiKey = props.getProperty("apiKey", "");
        xmppHost = props.getProperty("xmppHost", "127.0.0.1");
        xmppPort = props.getProperty("xmppPort", "5222");
        Log.i(LOGTAG, "apiKey=" + apiKey);
        Log.i(LOGTAG, "xmppHost=" + xmppHost);
        Log.i(LOGTAG, "xmppPort=" + xmppPort);

        sharedPrefs = context.getSharedPreferences(
                Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
        Editor editor = sharedPrefs.edit();
        editor.putString(Constants.API_KEY, apiKey);
        editor.putString(Constants.VERSION, version);
        editor.putString(Constants.XMPP_HOST, xmppHost);
        editor.putInt(Constants.XMPP_PORT, Integer.parseInt(xmppPort));
        editor.putString(Constants.CALLBACK_ACTIVITY_PACKAGE_NAME,
                callbackActivityPackageName);
        editor.putString(Constants.CALLBACK_ACTIVITY_CLASS_NAME,
                callbackActivityClassName);
        editor.commit();

        ChatActivity chatActivity  = new ChatActivity();
//        chatMsgReceiver  = chatActivity.getChatMsgReceiver();
    }

    public void registerChatMsgReceiver(){
        IntentFilter chatfilter = new IntentFilter();
        chatfilter.addAction(Constants.ACTION_SHOW_CHATMSG);
        chatfilter.addAction(Constants.ACTION_CHATMSG_CLICKED);
        chatfilter.addAction(Constants.ACTION_CHATMSG_CLEARED);
//        context.registerReceiver(chatMsgReceiver, chatfilter);
    }

    public void startService() {
        Thread serviceThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Intent intent = NotificationService.getIntent();
                intent.setClass(context,NotificationService.class);
                context.startService(intent);
            }
        });
        serviceThread.start();
    }

    public void stopService() {
        Intent intent = NotificationService.getIntent();
        context.stopService(intent);
    }


    private Properties loadProperties() {

        Properties props = new Properties();
        try {
            int id = context.getResources().getIdentifier("androidpn", "raw",
                    context.getPackageName());
            props.load(context.getResources().openRawResource(id));
        } catch (Exception e) {
            Log.e(LOGTAG, "Could not find the properties file.", e);
        }
        return props;
    }

    public void setNotificationIcon(int iconId) {
        Editor editor = sharedPrefs.edit();
        editor.putInt(Constants.NOTIFICATION_ICON, iconId);
        editor.commit();
    }

    public static void viewNotificationSettings(Context context) {
        Intent intent = new Intent().setClass(context,
                NotificationSettingsActivity.class);
        context.startActivity(intent);
    }

    /**
     * Set Alias
     *
     * @param alias
     */
    public void setAlias(final String alias) {
        final String username = sharedPrefs.getString(Constants.XMPP_USERNAME,
                "");
        if (TextUtils.isEmpty(alias) || TextUtils.isEmpty(username)) {
            return;
        }
        /**
         * NotificationService init();
         */
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                NotificationService notificationService = NotificationService
                        .getNotificationService();
                XmppManager xmppManager = notificationService.getXmppManager();

                if (xmppManager != null) {
                    if (!xmppManager.getAuthenticated()) {
                        try {
                            Log.d(LOGTAG,"wait for Authenticated...");
                            synchronized (xmppManager) {
                                xmppManager.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    Log.d(LOGTAG,"uthenticated already. send SetAliasIQ...");
                    SetAliasIQ setAliasIQ = new SetAliasIQ();
                    setAliasIQ.setType(IQ.Type.SET);
                    setAliasIQ.setUsername(username);
                    setAliasIQ.setAlias(alias);
                    xmppManager.getConnection().sendPacket(setAliasIQ);
                }
            }
        }).start();
    }

    /**
     * Set Tags
     * @param tagList
     */
    public void setTags(final List<String> tagList){
        final String username = sharedPrefs.getString(Constants.XMPP_USERNAME,
                "");
        if(tagList==null||tagList.isEmpty()||TextUtils.isEmpty(username)){
            return;
        }
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                NotificationService notificationService = NotificationService
                        .getNotificationService();
                XmppManager xmppManager = notificationService.getXmppManager();

                if (xmppManager != null) {
                    if (!xmppManager.getAuthenticated()) {
                        try {
                            Log.d(LOGTAG,"wait for Authenticated...");
                            synchronized (xmppManager) {
                                xmppManager.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    Log.d(LOGTAG,"uthenticated already. send SetTagsIQ...");
                    SetTagsIQ setTagsIQ = new SetTagsIQ();
                    setTagsIQ.setType(IQ.Type.SET);
                    setTagsIQ.setUsername(username);
                    setTagsIQ.setTaglList(tagList);
                    xmppManager.getConnection().sendPacket(setTagsIQ);
                }
            }
        }).start();
    }

    public void sendChatMsg(final String toUser,final String chatDate,final String chatMessage,final boolean chatMsgType){
        final String fromUser = sharedPrefs.getString(ConstantUtils.USER_ID,"");

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                NotificationService notificationService = NotificationService
                        .getNotificationService();
                XmppManager xmppManager = notificationService.getXmppManager();

                if (xmppManager != null) {
                    if (!xmppManager.getAuthenticated()) {
                        try {
                            Log.d(LOGTAG,"wait for Authenticated...");
                            synchronized (xmppManager) {
                                xmppManager.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    Log.d(LOGTAG, "uthenticated already send sendChatMsg...");
                    ChatMsgIQ chatMsgIQ = new ChatMsgIQ();
                    chatMsgIQ.setType(IQ.Type.SET);
                    chatMsgIQ.setFromuser(fromUser);
                    chatMsgIQ.setTouser(toUser);
                    chatMsgIQ.setDate(chatDate);
                    chatMsgIQ.setMessage(chatMessage);
                    chatMsgIQ.setMsgtype(Boolean.toString(chatMsgType));
                    chatMsgIQ.setUuid(null);
                    xmppManager.getConnection().sendPacket(chatMsgIQ);
                }
            }
        }).start();
    }
}
